﻿using Prism.Commands;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Config;
using SmartPlant.WinCore.Helper;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Windows.Input;

namespace SmartPlant.Modules.Base.ViewModels
{
    /// <summary>
    /// 配置服务器地址信息
    /// </summary>
    public class ServerSettingViewModel : DialogViewModelBase, IDialogAware
    {
        private DelegateCommand<object> _testDialogCommand;
        private IOAuthService _authService;
        private DelegateCommand<object> _dataLoadCommand;
        private bool _isBusy = false;
        private bool _isTest = false;
        private readonly BackgroundWorker backgroundWorker;

        public ServerSettingViewModel(IOAuthService authService, IDialogService dialog) : base(dialog)
        {
            _authService = authService;
            Title = "服务器地址配置";
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += this.OnBackgroundWorkerDoWork;
            backgroundWorker.RunWorkerCompleted += OnBackgroundWorkerComplete;
        }

        private string _serverAddr;
        public string ServerAddr
        {
            get { return _serverAddr; }
            set { SetProperty(ref _serverAddr, value); }
        }

        /// <summary>
        /// 当前是否处理忙碌状态。
        /// </summary>
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                if (this._isBusy != value)
                {
                    this._isBusy = value;
                    this.OnPropertyChanged("IsBusy");

                    if (this._isBusy && !backgroundWorker.IsBusy)
                    {
                        backgroundWorker.RunWorkerAsync();
                    }
                }
            }
        }

        public ICommand TestDialogCommand
        {
            get
            {
                if (_testDialogCommand != null) return _testDialogCommand;
                _testDialogCommand = new DelegateCommand<object>(ExecuteTestDialogCommand);
                return _testDialogCommand;
            }
        }

        public ICommand DataLoadCommand
        {
            get
            {
                if (_dataLoadCommand != null) return _dataLoadCommand;
                _dataLoadCommand = new DelegateCommand<object>(ExeDataLoadCommandAsync);
                return _dataLoadCommand;
            }
        }

        /// <summary>
        /// 数据加载完成。
        /// </summary>
        /// <param name="e"></param>
        private void OnBackgroundWorkerComplete(object sender, RunWorkerCompletedEventArgs e)
        {
            InvokeOnUIThread(() =>
            {
                this.IsBusy = false;
                var result = e.Result as RESTfulResult;
                _isTest = result.succeeded;
                if (result.succeeded)
                {
                    Dialog.ShowMessage("测试连接远程服务器成功!!!");
                }
                else
                {
                    LoggerHelper.Current.Error(result.errors.ToString());
                    Dialog.ShowAltert(result.errors.ToString());
                }
            });
        }
        private void ExecuteTestDialogCommand(object obj)
        {
            if (string.IsNullOrEmpty(this.ServerAddr))
            {
                Dialog.ShowAltert("测试连接远程服务器必须填写服务器地址！！！");
                return;
            }
            if (!CheckServerAddr())
            {
                Dialog.ShowAltert("服务器地址格式不正确！！！");
                return;
            }
            IsBusy = true;
        }
        private void OnBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var task = _authService.TestServerAsync(ServerAddr);
                while (!task.IsCompleted)
                {
                    Thread.Sleep(1000);
                }
                if (task.Exception != null)
                {
                    e.Result = new RESTfulResult { succeeded = false, errors = $"测试连接远程服务器失败：" + task.Exception.Message };
                }
                else
                {
                    e.Result = new RESTfulResult { succeeded = true };
                }

            }
            catch (Exception x)
            {
                e.Result = new RESTfulResult { succeeded = false, errors = $"测试连接远程服务器失败：" + x.Message };
            }
        }

        private void ExeDataLoadCommandAsync(object obj)
        {
            try
            {
                var config = ConfigHelper.ReadConfig();
                ServerAddr = config.ServerAddress;
            }
            catch (Exception x)
            {
                var xMessage = $"加载服务器配置信息失败：" + x.Message;
                LoggerHelper.Current.Error(xMessage, x);
                Dialog.ShowAltert(xMessage);
            }
        }

        protected override void onCloseDialogCommand(string parameter)
        {
            ButtonResult result = ButtonResult.None;
            if (parameter?.ToLower() == "ok")
            {
                if (ServerAddr.IsNullOrEmpty())
                {
                    Dialog.ShowAltert("服务器地址不能为空！！！");
                    return;
                }

                if (!CheckServerAddr())
                {
                    Dialog.ShowAltert("服务器地址格式不正确！！！");
                    return;
                }

                if (!_isTest)
                {
                    Dialog.ShowAltert("服务器地址测试连接失败，不能保存！！！");
                    return;
                }

                try
                {
                    var config = new SysConfig { ServerAddress = ServerAddr };
                    ConfigHelper.WriteConfig(config);
                    Dialog.ShowMessage("服务器配置信息保存成功!!!");
                    result = ButtonResult.OK;
                }
                catch (Exception x)
                {
                    var xMessage = $"写入服务器配置信息失败：" + x.Message;
                    LoggerHelper.Current.Error(xMessage, x);
                    Dialog.ShowAltert(xMessage);
                }
            }
            else if (parameter?.ToLower() == "cancel")
                result = ButtonResult.Cancel;
            RaiseRequestClose(new DialogResult(result));
        }

        private bool CheckServerAddr()
        {
            string reg = @"((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?";
            var match = Regex.Match(ServerAddr, reg);
            if (match.Success)
            {
                return true;
            }
#if DEBUG
            reg = @"((http|ftp|https)://)(localhost)(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?";
            match = Regex.Match(ServerAddr, reg);
            if (match.Success)
            {
                return true;
            }
#endif
            return false;
        }
    }
}
